#include "sensor_common.h"
#include "sensor_config.h"

// Constant definition

#if SAVIT_FILTER_LENGTH == 5
#define SAVIT_FILTER_COEF           {2,1,0,-1,-2}
#define SAVIT_FILTER_SCALE          10
#elif SAVIT_FILTER_LENGTH == 10
#define SAVIT_FILTER_COEF           {9,7,5,3,1,-1,-3,-5,-7,-9}
#define SAVIT_FILTER_SCALE          165
#elif SAVIT_FILTER_LENGTH == 15
#define SAVIT_FILTER_COEF           {7,6,5,4,3,2,1,0,-1,-2,-3,-4,-5,-6,-7}
#define SAVIT_FILTER_SCALE          280
#endif


// Private function declaration
static fixed32 PerMinute( fixed32 f32_value );


// Function definition

logical CountToDo( sensor_period_timer *tp_timer )
{
    tp_timer->u32_counter++;
    if ( tp_timer->u32_counter >= tp_timer->u32_period )
    {
        tp_timer->u32_counter = 0;
        return L_TRUE;
    }
    return L_FALSE;
}

logical CheckToDo( sensor_period_timer const *tp_timer )
{
    return ( tp_timer->u32_counter == 0 );
}


//fixed32 FirFilter( cycle_buffer const *tp_buffer )
//{
//    static int32 i32_firCoef[] = FIR_FILTER_COEF;
//    static filter_window t_firWin = { i32_firCoef,
//                                      FIR_FILTER_LENGTH,
//                                      0 };
//
//    return Buffer_Filter( tp_buffer, &t_firWin );
//}


fixed32 ChangePerMinute( cycle_buffer const *tp_buffer )
{
    fixed32 f32_ret;

    f32_ret = Buffer_Diff( tp_buffer, 0 );
    f32_ret = PerMinute( f32_ret );
    return f32_ret;
}

fixed32 ChangePerMinuteFilt( cycle_buffer const *tp_buffer )
{
    static int32 i32_savitCoef[] = SAVIT_FILTER_COEF;
    static filter_window t_savitWin = { i32_savitCoef,
                                        SAVIT_FILTER_LENGTH,
                                        SAVIT_FILTER_SCALE };

    fixed32 f32_ret;

    if (tp_buffer->u32_count < SAVIT_FILTER_LENGTH)
        return 0;

    f32_ret = Buffer_Filter( tp_buffer, &t_savitWin );
    f32_ret = PerMinute( f32_ret );
    return f32_ret;
}

static fixed32 PerMinute( fixed32 f32_value )
{
    f32_value *= SAMPLES_PER_HOUR;
    f32_value = S_DIV ( f32_value, MINUTES_PER_HOUR );
    return f32_value;
}
